package com.net.model.base.fragment;

import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.drug.lib.util.DLog;
import com.drug.lib.util.ToastUtil;
import com.drug.lib.view.CommonTitle;
import com.drug.lib.view.load.LoadStatus;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.ItemViewBinder;
import com.drug.lib.view.recycptr.RefreshRecyclerView;
import com.drug.lib.view.recycptr.bean.BaseEntity;
import com.net.model.base.Resource;
import com.net.model.databinding.BaseListFragmentBinding;
import com.net.model.utils.Constant;
import com.net.model.viewmodel.BaseViewModel;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public abstract class BaseVMListFragment<VM extends BaseViewModel> extends BaseLoadVBFragment<BaseListFragmentBinding>
        implements OnRefreshLoadMoreListener {
    protected VM mViewModel;

    protected DynamicRecyclerAdapter dynamicRecyclerAdapter;

    protected RefreshRecyclerView refreshRecyclerView;

    protected abstract void dataChange();

    public abstract void requestListData(int page, int size);

    @Override
    protected BaseListFragmentBinding getViewBinding() {
        return BaseListFragmentBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initialize() {
        createViewModel();
        dataChange();
        initRefreshView();
    }


    private void initRefreshView() {
        refreshRecyclerView = mBinding.rcyLibListView;
        refreshRecyclerView.setRecyclerLoadListener(this);
        refreshRecyclerView.initView();
        refreshRecyclerView.initRecyclerView();
        loadPage.getBuilder().setRetryButtonClick(() -> requestListData(refreshRecyclerView.getPage(), refreshRecyclerView.getSize()));

    }

    public void setAdapter() {
        setAdapter(null);
    }

    public void setAdapter(List<BaseEntity> baseEntities) {
        refreshRecyclerView.setAdapter(baseEntities);
    }

    public void setEnablePureScrollMode(boolean canPureScrollMode) {
        refreshRecyclerView.setEnablePureScrollMode(canPureScrollMode);
    }


    public void setTitle(String title) {
        mBinding.basePLNavigationBar.setTitleText(title);
    }

    public CommonTitle getCommonTitle() {
        return mBinding.basePLNavigationBar;
    }

    public void scrollToPosition(int position) {
        RecyclerView recyclerView = refreshRecyclerView.getRecyclerView();
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        linearLayoutManager.scrollToPositionWithOffset(position, 0);
    }

    public void createViewModel() {
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshRecyclerView.setPage(1);
        requestListData(1, refreshRecyclerView.getSize());
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshRecyclerView.setPage(refreshRecyclerView.getPage() + 1);
        requestListData(refreshRecyclerView.getPage(), refreshRecyclerView.getSize());
    }

    /**
     * description: 在头部添加布局
     *
     * @param view
     * @author: zhouhequan
     * @date: 2023/5/19 9:53
     * @return: void
     */
    protected void addHeadView(View view) {
        mBinding.fltBaseHead.setVisibility(View.VISIBLE);
        mBinding.fltBaseHead.addView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    }

    /**
     * description: 在底部添加布局
     *
     * @param view
     * @author: zhouhequan
     * @date: 2023/5/19 9:53
     * @return: void
     */

    public void addBottomView(View view) {
        mBinding.fltBaseBottom.setVisibility(View.VISIBLE);
        mBinding.fltBaseBottom.addView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
    }

    public void removeBottomView() {
        mBinding.fltBaseBottom.setVisibility(View.GONE);
    }

    /**
     * @param clazz
     * @param binder
     * @param <T>
     */
    public <T> void register(Class<? extends T> clazz, ItemViewBinder<T, ?> binder) {
        refreshRecyclerView.register(clazz, binder);
    }

    /**
     * description: 刷新列表
     *
     * @param position 刷新对应项
     * @author: zhouhequan
     * @date: 2023/5/19 9:52
     * @return: void
     */

    public void notifyDataSetChanged(int position) {
        if (dynamicRecyclerAdapter == null) return;
        if (position == -1) dynamicRecyclerAdapter.notifyDataSetChanged();
        else dynamicRecyclerAdapter.notifyItemChanged(position);
    }

    /**
     * description: 将数据装填到ui
     *
     * @param list
     * @author: zhouhequan
     * @date: 2023/5/19 9:53
     * @return: void
     */

    protected void addData(List<? extends BaseEntity> list) {
        int page = refreshRecyclerView.getPage();
        //刷新失败
        if (list == null) {
            if (page == 1) {
                getHandler().postDelayed(() -> loadPage.getBuilder().show(LoadStatus.LOAD_FAILD), 2000);
                refreshRecyclerView.refreshComplete(false);
            } else {
                refreshRecyclerView.loadMoreComplete(false);
            }
            return;
        }


        if (list.size() == 0) {
            if (page == 1) {
                getHandler().postDelayed(() -> loadPage.getBuilder().show(LoadStatus.NODATA), 2000);
                refreshRecyclerView.refreshComplete(true);
            } else {
                refreshRecyclerView.loadMoreNoMoreData();
            }
            return;
        }


        int size = list.size();
        boolean isMoreData = size >= refreshRecyclerView.getSize();
        if (page == 1) {
            refreshRecyclerView.refreshComplete(true);
            refreshRecyclerView.setNoMoreData(!isMoreData);
            refreshRecyclerView.refreshData(list);
            getHandler().postDelayed(() -> loadPage.getBuilder().dismiss(), 2000);
        } else {
            refreshRecyclerView.loadMoreComplete(true);
            refreshRecyclerView.setNoMoreData(!isMoreData);
            refreshRecyclerView.loadMoreData(list);
        }
    }

    public void addItemData(BaseEntity baseEntity, int position) {
        refreshRecyclerView.addDataToList(baseEntity, position);
    }


    /**
     * description: 删除列表某一项
     *
     * @param baseEntity
     * @author: zhouhequan
     * @date: 2023/5/19 9:52
     * @return: void
     */
    public void deleteItemData(BaseEntity baseEntity) {
        List<BaseEntity> baseEntities = refreshRecyclerView.getListData();
        if (baseEntities != null && baseEntities.size() != 0) {
            for (BaseEntity baseEntity1 : baseEntities) {
                if (baseEntity.hashCode() == baseEntity1.hashCode()) {
                    baseEntities.remove(baseEntity1);
                    break;
                }
            }
        }
        if (baseEntities == null || baseEntities.size() == 0)
            loadPage.getBuilder().show(LoadStatus.NODATA);
        notifyDataSetChanged(-1);
    }

    /**
     * description: 删除列表某一项
     *
     * @param position
     * @author: zhouhequan
     * @date: 2023/5/19 9:52
     * @return: void
     */

    public BaseEntity deleteItemData(int position) {
        List<BaseEntity> baseEntities = refreshRecyclerView.getListData();
        BaseEntity baseEntity = null;
        if (baseEntities != null && position < baseEntities.size()) {
            baseEntity = baseEntities.get(position);
            baseEntities.remove(baseEntity);
        }
        if (baseEntities == null || baseEntities.size() == 0)
            loadPage.getBuilder().show(LoadStatus.NODATA);
        notifyDataSetChanged(-1);
        return baseEntity;
    }

    /**
     * description: 重置列表信息（置空）
     *
     * @param
     * @author: zhouhequan
     * @date: 2023/5/19 9:51
     * @return: void
     */

    public void resetListInfo() {
        this.refreshRecyclerView.getListData().clear();
        loadPage.getBuilder().show(LoadStatus.NODATA);
        notifyDataSetChanged(-1);
    }

    public abstract class OnCallback<T> implements Resource.OnHandleCallback<T> {
        boolean isLoading = false;

        public OnCallback(boolean isLoading) {
            this.isLoading = isLoading;
        }

        public OnCallback() {
        }

        @Override
        public void onLoading() {
            if (isLoading) loadPage.getBuilder().show(LoadStatus.LOADING);
            DLog.d("加载中.....");
        }


        @Override
        public void onFailure(Integer code, String message) {
            refreshRecyclerView.refreshComplete(false);
            refreshRecyclerView.loadMoreComplete(false);
            if (loadPage.isViEnable()) {
                if (code == Constant.EMPTY_DATA_ERROR) {
                    getHandler().postDelayed(() -> loadPage.getBuilder().dismiss(), 2000);
                } else {
                    getHandler().postDelayed(() -> loadPage.getBuilder().setMessage(message).show(LoadStatus.LOAD_FAILD), 2000);
                }
                return;
            }
            if (code != Constant.EMPTY_DATA_ERROR) {
                ToastUtil.show(message);
            }
        }

        @Override
        public void onCompleted() {
            DLog.d("加载完成");
//            if (isLoading) {
//                getHandler().postDelayed(() -> loadPage.getBuilder().dismiss(), 2000);
//            }
            refreshRecyclerView.refreshComplete(true);
            refreshRecyclerView.loadMoreComplete(true);
        }

        @Override
        public void onProgress(int precent, long total) {

        }
    }
}
